﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using StockFinder.Model;
using StockFinder.Model.Enumerations;
using StockFinder.Network;
using StockFinder.StockLists.SymbolListEnumerators;

namespace StockFinder.StockLists.Indexes
{
    public class FinvizOnlineDowJonesStockList : YahooFinanceOnlinePriceLoaderSymbolListEnumerator
    {
        const string NASDAQ_SYMBOLS_URL = "http://finviz.com/export.ashx?v=111&f=exch_nasd,idx_dji";
        const string NYSE_SYMBOLS_URL = "http://finviz.com/export.ashx?v=111&f=exch_nyse,idx_dji";
        const string AMEX_SYMBOLS_URL = "http://finviz.com/export.ashx?v=111&f=exch_amex,idx_dji";

        private readonly Dictionary<Exchange, string> _ExchangeUrls = new Dictionary<Exchange, string>()
        {
                {Exchange.NASDAQ, NASDAQ_SYMBOLS_URL},
                {Exchange.NYSE, NYSE_SYMBOLS_URL},
                {Exchange.AMEX, AMEX_SYMBOLS_URL}
        }; 

        public FinvizOnlineDowJonesStockList()
        {
            Name = "Down Jones";
        }

        protected override List<Symbol> GetSymbols()
        {
            var stockIndexList = new List<Symbol>();

            using (var webClient = new ProxiedWebClient())
            {
                foreach (var exchangeUrl in _ExchangeUrls)
                {
                    var url = exchangeUrl.Value;
                    var exchange = exchangeUrl.Key;

                    var pageSource = webClient.DownloadString(url);

                    var lines = pageSource.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1);

                    stockIndexList.AddRange(from line in lines
                                            select line.Split(new[] { "," }, StringSplitOptions.None)
                                                into cells
                                                select cells[1].Replace("\"", "")
                                                    into ticker
                                                    select new Symbol { Name = ticker, Exchange = exchange });
                }
            }

            return stockIndexList;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
